﻿var substringMatcher = function (strs) {
    return function findMatches(q, cb) {
        var matches, substringRegex;

        // an array that will be populated with substring matches
        matches = [];

        // regex used to determine if a string contains the substring `q`
        substrRegex = new RegExp(q, 'i');

        // iterate through the pool of strings and for any string that
        // contains the substring `q`, add it to the `matches` array
        $.each(strs, function (i, str) {
            if (substrRegex.test(str)) {
                matches.push(str);
            }
        });

        cb(matches);
    };
};

function GetAllUsers(currentWebUrl) {
    $.ajax(
    {
        url: currentWebUrl + "/_api/Web/SiteUsers",
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: GetAllUsers_Success,
        error: errorHandler
    });
}

function GetAllUsers_Success(data) {
    var txtAllUsers = "";

    $.each(data.d.results, function (index, result) {
        if (txtAllUsers.length > 0) {
            txtAllUsers = txtAllUsers + ", ";
        }
        txtAllUsers += "{ \"value\": \"" + result.Id + "\" , \"label\" : \"" + result.Title + "\" } ";
    });

    txtAllUsers = "[" + txtAllUsers + "]";
    txtAllUsers = txtAllUsers.replace(/\\/g, "\\\\");

    var arrayAllUsers = JSON.parse(txtAllUsers);

    $("#txtSelectUser").autocomplete({
        source: arrayAllUsers,
        select: function (event, ui) {
            $("#txtSelectUser").val(ui.item.label);
            $("#txtSelectUser").attr("UserId", ui.item.value);
            return false;
        }
    });
}

function GetAllGroups(currentWebUrl) {
    $.ajax(
    {
        url: currentWebUrl + "/_api/Web/SiteGroups",
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: GetAllGroups_Success,
        error: errorHandler
    });
}

function GetAllGroups_Success(data) {
    var txtAllGroups = "";

    $.each(data.d.results, function (index, result) {
        if (txtAllGroups.length > 0) {
            txtAllGroups = txtAllGroups + ", ";
        }
        txtAllGroups += "{ \"value\": \"" + result.Id + "\" , \"label\" : \"" + result.LoginName + "\" } ";
    });

    txtAllGroups = "[" + txtAllGroups + "]";
    txtAllGroups = txtAllGroups.replace(/\\/g, "\\\\");

    var arrayAllGroups = JSON.parse(txtAllGroups);

    $("#txtSelectMembershipGroup").autocomplete({
        source: arrayAllGroups,
        select: function (event, ui) {
            $("#txtSelectMembershipGroup").val(ui.item.label);
            $("#txtSelectMembershipGroup").attr("GroupId", ui.item.value);
            return false;
        }
    });
}

function RenderUserOptions(fieldInternalName, selectedOperatorValue, txtPropertyValueId) {
    InitUserSelection();
    ShowSelectUserValueDialog(fieldInternalName, selectedOperatorValue, txtPropertyValueId);
}

function InitUserSelection() {
    $.each($("input[name='userSelectionType']:checked"), function (index, value) {
        console.log(value);
        value.checked = false;
    });

    $('#divSpecificUser').hide();
    $('#divMembership').hide();

    $('#txtSelectUser').val('');
    $("#ddlSelectMembershipType").val('');
    $('#txtSelectMembershipGroup').val('');
    $('#divSelectMembershipGroup').hide();
    $("#lblMembership").text('');
}

function ValidateCamlInputForUser(fieldInternalName, selectedOperatorValue, txtPropertyValueId) {
    var selectedUserValue = "";
    var userSelectionTypeValue = $("input[name='userSelectionType']:checked").val();
    var camlQueryNode = "";

    if (!userSelectionTypeValue || userSelectionTypeValue.lenth <= 0) {
        ShowValidationMessage("selectUserValueDiv", "Please select user");
        return false;
    }
    else {
        if (userSelectionTypeValue === "currentUser") {
            selectedUserValue = "<UserID />";
            camlQueryNode = "<" + selectedOperatorValue + ">" +
                                 "<FieldRef Name='" + fieldInternalName + "' />" +
                                 "<Value Type='Integer'>" +
                                    "<UserID />" +
                                 "</Value>" +
                              "</" + selectedOperatorValue + ">";
        }
        else if (userSelectionTypeValue === "specificUser") {
            var selectedUserValue = $("#txtSelectUser").val();

            if (selectedUserValue === "") {
                ShowValidationMessage("divSpecificUser", "Please select user");
                return false;
            }
            camlQueryNode = "<" + selectedOperatorValue + ">" +
                                 "<FieldRef Name='" + fieldInternalName + "' />" +
                                 "<Value Type='User'>" +
                                    selectedUserValue +
                                 "</Value>" +
                              "</" + selectedOperatorValue + ">";
        }
        else if (userSelectionTypeValue === "membership") {
            var selectedMembershipType = $("#ddlSelectMembershipType option:selected").val();

            if (typeof selectedMembershipType === "undefined" || selectedMembershipType === "") {
                ShowValidationMessage("divSelectMembershipType", "Please select membership type");
                return false;
            }

            if (selectedMembershipType === "SPGroup") {
                var selectedMembershipGroup = $("#txtSelectMembershipGroup").val();
                if (typeof selectedMembershipGroup === "undefined" || selectedMembershipGroup === "") {
                    ShowValidationMessage("divSelectMembershipGroup", "Please select membership group");
                    return false;
                }

                selectedUserValue = "<FieldRef Name='Author' />";
                camlQueryNode = "<Membership Type='SPGroup' ID='" +$("#txtSelectMembershipGroup").attr("GroupId") + "'>" +
                                     "<FieldRef Name='" + fieldInternalName + "' />" +
                                  "</Membership>";
            }
            else {
                selectedUserValue = "<FieldRef Name='Author' />";
                camlQueryNode = "<Membership Type='" + selectedMembershipType + "'>" +
                                     "<FieldRef Name='" + fieldInternalName + "' />" +
                                  "</Membership>";
            }
        }
        else {
            alert("Invalid value for 'userSelectionTypeValue': " + userSelectionTypeValue);
            return false;
        }
    }

    $("#" + txtPropertyValueId).attr("UserSelectionType", userSelectionTypeValue);
    $("#" + txtPropertyValueId).attr("CamlQueryNode", camlQueryNode);
    $("#" + txtPropertyValueId).val(selectedUserValue);
    return true;
}

function btnSelectUserValue_onClick(object, fieldInternalName, selectedOperatorValue, txtPropertyValueId) {
    if (ValidateCamlInputForUser(fieldInternalName, selectedOperatorValue, txtPropertyValueId)) {
        $('#selectUserValueDialog').modal('hide')
    }
}

function ShowSelectUserValueDialog(fieldInternalName, selectedOperatorValue, txtPropertyValueId) {
    $("#btnSelectUserValue").attr("onclick", "return btnSelectUserValue_onClick(this, '" + fieldInternalName + "', '" + selectedOperatorValue + "', '" + txtPropertyValueId + "');");
    $('#selectUserValueDialog').modal();
}

function chkSelectionType_onChange(object) {
    if (object.value === "currentUser") {
        $('#divSpecificUser').hide();
        $('#divMembership').hide();
    }
    else if (object.value === "specificUser") {
        $('#divSpecificUser').show();
        $('#divMembership').hide();
    }
    else if (object.value === "membership") {
        $('#divSpecificUser').hide();
        $('#divMembership').show();
    }
}

function ddlSelectMembershipType_onChange(object) {
    var selectedMembershipType = $(object).val();
    var infoMessage = "";

    $("#divSelectMembershipGroup").hide();

    if (selectedMembershipType === "CurrentUserGroups") {
        infoMessage = "Tasks assigned to current user or to groups to which current user belongs";
    }
    else if (selectedMembershipType === "SPGroup") {
        infoMessage = "Tasks assigned to members of this group";
        $("#divSelectMembershipGroup").show();
    }
    else if (selectedMembershipType === "SPGroup.Groups") {
        infoMessage = "Tasks assigned to groups";
    }
    else if (selectedMembershipType === "SPGroup.AllUsers") {
        infoMessage = "Tasks assigned directly to user";
    }
    else if (selectedMembershipType === "SPGroup.Users") {
        infoMessage = "Tasks assigned to users who have received rights to the site directly";
    }

    $("#lblMembership").text(infoMessage);
}